function [board,cntFences] = findFences(board,bluewoCircles,demo)
%findFences Hledani ohrad
%   board - vstup/vystup(s podbarvenim pastvin) hraci desky
%   cntFences - pocet pastvin
%   bluewoCircles - modry rastr bez kruhu

% smazani sumu
bluewoCircles=imopen(bluewoCircles,ones(3));

% spojeni ohrad
dil=round(size(board,2)/13);
ohrady=imdilate(bluewoCircles,ones(dil));
if demo
  figure
  imshow(ohrady)
  title('Hledani pastvin')
end
% pocet der
euler=regionprops(ohrady,'EulerNumber');
if isempty(euler)
  cntFences=0; % bez diry neni ohrada
else
  cntFences=length(euler)-sum([euler(:).EulerNumber]);
  negohrady=~ohrady; % prechod na pastviny v popredi
  % odstraneni pozadi a eroze ohrad, tj. dilatace pastvin
  [r,c]=size(negohrady);
  ohrady=imdilate(~bwselect(negohrady,1,1)&~bwselect(negohrady,c,r)&~bwselect(negohrady,c,1)&~bwselect(negohrady,1,r)&negohrady,ones(dil));
  check=regionprops(ohrady,'Area','Centroid');
  for i=1:length(check)
    if check(i).Area<(2*dil*dil) % kdyby nahodou zbyl okrajovy bod
      ohrady=ohrady&~bwselect(ohrady,check(i).Centroid(1),check(i).Centroid(2));
    end
  end
  if demo
    figure
    imshow(ohrady)
    title('Nalezene pastviny')
  end
  % podbarveni
  board(:,:,1)=max(255*uint8(ohrady),board(:,:,1));
end
end

